package com.hc;

import org.junit.Test;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * java内置四大核心函数式接口
 */
public class TestLambda3 {


    /**
     * Predicate<T,R> 断言型接口
     */

    @Test
    public void test4(){
        List<String> list = Arrays.asList("hello","hc","lambda","wwww","ok");
        List<String> strings = filterStr(list, (s) -> s.length() > 3);
        for (String s:strings){
            System.out.println(s);
        }
    }

    //需求:满足条件的字符串,放入集合中
    public List<String> filterStr(List<String> list, Predicate<String> pre){
        List<String> stringList =new ArrayList<>();

        for (String str:list){
            if (pre.test(str)){
                stringList.add(str);
            }
        }
        return stringList;
    }


    /**
     * Function<T,R> 函数型接口
     */

    @Test
    public void test3(){
        String newStr = strHandler("\t\t\t 输出:加油", (str) -> str.trim());//trim去除首位空格
        System.out.println(newStr);

        String handler = strHandler("输出:加油", (str) -> str.substring(3, 5));
        System.out.println(handler);
    }



    //需求用于处理字符串
    public String strHandler(String str, Function<String,String> fun){
        return fun.apply(str);
    }




    /**
     * Supplier<T> 供给型接口
     */

    @Test
    public void test2() {
        List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));
        for (Integer num:numList){
            System.out.println(num);
        }
    }

    //需求:产生指定个数的整数,并放入集合中
    public List<Integer> getNumList(int num, Supplier<Integer> sup) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            Integer number = sup.get();
            list.add(number);
        }

        return list;
    }


    /**
     * Consumer<T>消费型接口
     */

    @Test
    public void test1() {
        happy(10000, (m) -> System.out.println("输出:大保健每次消费:" + m + "元"));
    }

    public void happy(double money, Consumer<Double> con) {
        con.accept(money);
    }

}
